package com.easysoft.framework.aop;

import com.easysoft.commons.utils.JSONUtils;
import com.easysoft.commons.utils.WebConstants;
import com.easysoft.framework.annotation.logs.SystemControllerLog;
import com.easysoft.framework.logs.model.SysLogs;
import com.easysoft.framework.logs.service.SysLogsService;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.Map;

/**
 * Created by try on 2017/7/28.
 */
@Aspect
@Component
public  class SysControllerAspect {

    private final static Logger logger =LoggerFactory.getLogger(SysControllerAspect.class);

    @Autowired
    @Qualifier("service.SysLogsService")
    private SysLogsService sysLogsService;

    public  SysControllerAspect(){
        logger.info("实例化了没有");
    }


    private String requestPath = null ; // 请求地址
    private String userId = "" ; //  用户Id
    private Map<?,?> inputParamMap = null ; // 传入参数
    private Map<String, Object> outputParamMap = null; // 存放输出结果
    private long startTimeMillis = 0; // 开始时间
    private long endTimeMillis = 0; // 结束时间
    private HttpServletRequest request = null;

    /**
     * 方法调用前触发   记录开始时间
     * @param joinPoint
     */
    public void before(JoinPoint joinPoint){
        request = getHttpServletRequest();
        //fileName  为例子
        Object obj =request.getParameter("fileName");
        userId = (String) request.getSession().getAttribute(WebConstants.SESSION_USER_ID);
        startTimeMillis = System.currentTimeMillis(); //记录方法开始执行的时间
    }

    /**
     * 方法调用后触发   记录结束时间
     * @param joinPoint
     */
    public  void after(JoinPoint joinPoint) {
        request = getHttpServletRequest();
        String targetName = joinPoint.getTarget().getClass().getName();
        String methodName = joinPoint.getSignature().getName();
        Object[] arguments = joinPoint.getArgs();
        String ip = request.getRemoteAddr();
        //获取用户请求方法的参数并序列化为JSON格式字符串
        String params = "";
        if (arguments!=  null && arguments.length > 0) {
            for ( int i = 0; i < arguments.length; i++) {
                params += JSONUtils.object2Json(arguments[i]) + ";";
            }
        }
        Class targetClass = null;
        try {
            targetClass = Class.forName(targetName);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        Method[] methods = targetClass.getMethods();
        String description = "";
        for (Method method : methods) {
            if (method.getName().equals(methodName)) {
                Class[] clazzs = method.getParameterTypes();
                if (clazzs!=null&&clazzs.length == arguments.length&&method.getAnnotation(SystemControllerLog.class)!=null) {
                    description = method.getAnnotation(SystemControllerLog.class).description();
                    break;
                }
            }
        }
        endTimeMillis = System.currentTimeMillis();
        //格式化开始时间
        String startTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(startTimeMillis);
        //格式化结束时间
        String endTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(endTimeMillis);

        Object obj =request.getParameter("fileName");
        logger.info("方法调用后: " + obj);
        logger.info(" 操作人: "+userId+" 操作方法: "+description+" 操作开始时间: "+startTime +" 操作结束时间: "+endTime);

        //保存日志操作
        SysLogs sysLogs = new  SysLogs();
        sysLogs.setUserId(userId);
        sysLogs.setOperation(description);
        sysLogs.setParams(params);
        sysLogs.setIp(ip);
        sysLogs.setMothod(targetName +"." + methodName + "()");
        sysLogsService.addSysLogs(sysLogs);
    }

    /**
     * 获取request
     * @return
     */
    public HttpServletRequest getHttpServletRequest(){
        RequestAttributes ra = RequestContextHolder.getRequestAttributes();
        ServletRequestAttributes sra = (ServletRequestAttributes)ra;
        HttpServletRequest request = sra.getRequest();
        return request;
    }

    /**
     * 环绕触发
     * @param joinPoint
     * @return
     * @throws Throwable
     */
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable {

        return null;
    }



}

